<?php


namespace App\Http\Controllers\Admin;


use App\Http\Common\BaseController;
use App\Models\Weekly;
use App\Models\WeeklyLabel;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;
use App\Models\Role;
use App\Models\User;
use App\Models\UserRole;
use App\Models\AdminFunctions;
use App\Models\Notice;

class WeekliesController extends BaseController
{
    /**
     * 获取所有周报
     * @param Request $request
     * @param $user_id
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\Routing\ResponseFactory|\Illuminate\Http\Response
     */
    public function getWeekly(Request $request){
        $grades = $request->input('grades',0);
        $week = $request->get('week');
        $page = $request->input('page', 1);
        $semester = $request->input('semester', $this->getNewSemester());
        $is_del = $request->get('is_del');
        $user_id =$request->userId;
        $role_id = $this->getUserRole($user_id);

        $weekly = Weekly::where('semesters_id','=',$semester);
        //权限为成员或组长
        if( $role_id == 2 )$weekly = $weekly->where('user_id','=', $user_id)->where('is_deleted','=', 0);
        if( $role_id == 3 )$weekly = $weekly->where('user_id','=', $user_id)->where('is_deleted','=', 0);

        if (isset($is_del)) $weekly = $weekly->where('is_deleted','=', $is_del);

        if (isset($week)) $weekly = $weekly->where('weeks','=', $week);
        $pageNum  = ($page-1) * 20;
        $weekly = $weekly
            ->join('users','users.id','=','weeklies.user_id')
            ->join('grades','grades.id','=','users.grade_id')
            ->offset($pageNum)
            ->limit(20)
            ->get(['weeklies.id','weeklies.weeks','users.grade_id','weeklies.date','weeklies.title','users.username','grades.grade','weeklies.is_deleted as status']);

        if ($grades!=0) {
            $weekly_list = array();
            foreach ($weekly as $key){
                if ($key['grade_id'] == $grades){
                    $data = Weekly::join('weekly_labels', 'weeklies.id', 'weekly_id')
                        ->join('labels', 'weekly_labels.label_id', 'labels.id')
                        ->where('weeklies.id', $key['id'])
                        ->pluck('labels.label');
                    $key['label'] =$data;
                    $key['date'] = $this->switchTime($key['date']);
                    array_push($weekly_list,$key);
                }
            }
            return $this->returnJson(self::SUCCESS,'cg',$weekly_list);
        }
        foreach ($weekly as $key){
            $data = Weekly::join('weekly_labels', 'weeklies.id', 'weekly_id')
                ->join('labels', 'weekly_labels.label_id', 'labels.id')
                ->where('weeklies.id', $key['id'])
                ->pluck('labels.label');
            $key['label'] =$data;
            $key['date'] = $this->switchTime($key['date']);
        }
        return $this->returnJson(self::SUCCESS,'成功',$weekly);
    }


    /**
     * 管理员删除用户的周报
     * @param Request $request
     * @param $weekly_id
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\Routing\ResponseFactory|\Illuminate\Http\Response
     */
    public function delWeekly(Request $request,$weekly_id){
        $admin_id = $request->userId;

        $weekly =Weekly::where('id', '=' ,$weekly_id)->first(['date','user_id']);
        if (!$weekly){
            return $this->returnJson(self::FIELD_ERROR,'无此周报');
        }
        $content = $this->mkNoticeContent($admin_id,$weekly['user_id'],"删除了". $this->switchTime($weekly['date']) ."发布的周报");

        //创建启动事务
        DB::beginTransaction();
        try {
           Weekly::where('id','=',$weekly_id)->update(['is_deleted'=>1]);

            Weekly::where('id','=',$weekly_id)->delete();

            $this->creatNotice(4,$weekly['user_id'],$content);
            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return $this->returnJson(self::DATA_NOTFOUND,'该数据可能已被删除',$content);
        }

        return $this->returnJson(self::SUCCESS,'成功',$content);
    }

    /**
     * 获取未完成的周报
     * @param Request $request
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\Routing\ResponseFactory|\Illuminate\Http\Response
     */
    public function selOkWeely(Request $request){
        $weeks = $request->input('week',0);
        $grade = $request->input('grade',0);

        if ($grade == 0){
            $userInfo = User::where([]);
        }else{
            $userInfo = User::where('grade_id' ,'=' ,$grade);
        }
        $userInfo = $userInfo
            ->join('user_roles','user_roles.user_id','users.id')
            ->join('roles','roles.id','user_roles.role_id')
            ->join('grades','grades.id','users.grade_id')
            ->get(['users.id','users.username','users.phone','roles.name as roles_name','grades.grade']);

        $date['total'] =count($userInfo);

        $user_list = array();
        $unpub=0;
        $pub=0;

        if ($weeks == 0){
            $weeks = $this->getNewWeeks();
        }

        foreach ($userInfo as $key){
            $have = Weekly::where(['semesters_id'=>$this->getNewSemester(),'weeks'=>$weeks,'user_id'=>$key['id'],'is_deleted'=>0])->count();
            if ($have==0){
                $unpub += 1;
                array_push($user_list,$key);
            }else{
                $pub += 1;
            }
        }
        $date['unpub'] = $unpub;
        $date['pub'] = $pub;
        //如果此年级没人
        if ($date['total'] == 0){
            $date['res'] ='0%';
        }else{
            $date['res'] =number_format($pub/(count($userInfo)),3) * 100 . '%';
        }

        $date['list'] = $user_list;
        return $this->returnJson(self::SUCCESS,'成功' ,$date);
    }

    /**
     * 用户删除周报
     * @param Request $request
     * @param $weekly_id
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\Routing\ResponseFactory|\Illuminate\Http\Response\
     */
    public function delUserWeekly(Request $request,$weekly_id){

        //创建启动事务
        DB::beginTransaction();
        try {
            $weekly = Weekly::where('id', '=' ,$weekly_id)->get(['date','user_id'])[0];

            Weekly::where('id','=',$weekly_id)->update(['is_deleted'=>1]);

            $admin_id = $request->userId;
            $content = $this->mkNoticeContent($admin_id,'',$this->switchTime($weekly['date']) ."发布的周报",3);
            $this->creatNotice(4,$weekly['user_id'],$content);
            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return $this->returnJson(self::DATA_NOTFOUND,'该数据可能已被删除' );
        }

        return $this->returnJson(self::SUCCESS,'成功');
    }

    /**
     *  修改周报
     * @param Request $request
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\Routing\ResponseFactory|\Illuminate\Http\Response
     */
    public function updateWeekly(Request  $request){
        $weekly_id = $request->post('weekly_id');
        $title = $request->post('title');
        $content = $request->post('content');
        $edit = $request->post('edit');
        $label = $request->post('label');

        $updateList = array();
        if (!empty($title)) $updateList['title'] = $title;
        if (!empty($content)) $updateList['content'] =$content;
        if (!empty($edit)) $updateList['edit'] =$edit;

        try {
            if (!empty($label)){
                foreach ($label as $key){
                    WeeklyLabel::where('weekly_id','='.$weekly_id)->update([
                        'label_id'=>$key
                    ]);
                }
            }
            if (empty($updateList))  return $this->returnJson(self::SUCCESS,'成功');
            Weekly::where('id','=',$weekly_id)->update($updateList);
        } catch (\Exception $e) {
            return $this->returnJson(self::ERROR,'数据未修改',$e);
        }
        return $this->returnJson(self::SUCCESS,'成功');

    }
}
